<template>
  <div class="search-container">
    <div class="search-fixed">
      <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="springgreen"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShow = false"
        class="search-form"
      />
    </form>
    </div>
    <!-- 获取焦点，没输入内容，显示历史记录 -->
    <!-- 有焦点，按下回车，显示搜索结果 -->
    <!-- 搜索结果 -->
    <searchResult v-if="isShow" :searchText="searchText"></searchResult>
    <!-- 联想关键词 -->
    <searchSuggestion @search="onSearch" v-else-if="searchText" :searchText="searchText"></searchSuggestion>
     <!-- 历史记录 -->
    <searchHistory  @search="onSearch" v-else :searchHistory="searchHistory"></searchHistory>
  </div>
</template>

<script>
// 引入历史记录组件
import searchHistory from '@/views/search/components/searchHistory'
// 引入联想词组件
import searchSuggestion from '@/views/search/components/searchSuggestion'
// 引入搜索结果组件
import searchResult from '@/views/search/components/searchResult'
import { setItem, getItem } from '@/utils/stroage'
export default {
  data () {
    return {
      searchText: '', // 输入内容
      isShow: false, // 控制不同搜索内容的显示
      searchHistory: getItem('search-history') || [] // 搜索历史记录
    }
  },
  methods: {
    onSearch (text) {
      this.isShow = true
      // 储存搜索历史记录 要求：最新的在最前 不重复
      const index = this.searchHistory.indexOf(text)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(text)
      this.searchText = text
    },
    onCancel () {
      this.$router.push('/')
    }
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  },
  watch: {
    searchHistory () {
      setItem('search-history', this.searchHistory)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 110px;
  .van-search__action {
    color: #fff;
  }
}
.search-fixed {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 2;
}
</style>
